<template>
  <el-dialog
    :visible="visible"
    title="数据下载"
    width="500px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <div class="download-content">
      <div class="download-item" v-for="item in downloadItems" :key="item.id">
        <div class="item-left">
          <span class="item-name">{{ item.name }}</span>
        </div>
        <div class="item-right">
          <el-button
            :type="item.enabled ? 'primary' : 'info'"
            :disabled="!item.enabled"
            :loading="item.loading"
            size="small"
            @click="handleDownload(item)"
          >
            {{ item.enabled ? '下载' : '暂未开放' }}
          </el-button>
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script setup>
import { ref, computed } from 'vue'
import { Message } from 'element-ui'
import { downloadSatisfaction } from '@/api/question'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['close'])

const downloadItems = ref([
  {
    id: 'template',
    name: '模板数据',
    enabled: true,
    loading: false,
    filePath: window.templatePathUrl + '/模板数据.gdb.zip',
    fileName: '模板数据.gdb.zip'
  },
  {
    id: 'survey',
    name: '城市体检调查数据',
    enabled: false,
    loading: false,
    filePath: '',
    fileName: ''
  },
  {
    id: 'satisfaction',
    name: '满意度调查问卷',
    enabled: true,
    loading: false,
    filePath:  window.templatePathUrl + '/data/export/excel/download',
    fileName: '满意度调查问卷.xls'
  }
])

const handleDownload = async (item) => {
  if (!item.enabled) return
  
  if (item.id === 'satisfaction') {
    handleDownloadSatisfaction(item)
    return
  }
  item.loading = true
  try {
    const response = await fetch(item.filePath)
    if (response.ok) {
      console.log('下载路径:', item.filePath)
    } else {
      throw new Error(`HTTP ${response.status}`)
    }

    const blob = await response.blob()
    const url = URL.createObjectURL(blob)

    const link = document.createElement('a')
    link.href = url
    link.download = item.fileName
    link.style.display = 'none'

    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)

    URL.revokeObjectURL(url)

    Message.success('下载成功')
  } catch (error) {
    console.error('下载失败:', error)
    Message.error(`下载失败: ${error.message}`)
  } finally {
    item.loading = false
  }
}

const handleDownloadSatisfaction = async (item) => {
  // 找到满意度调查问卷的item并设置loading状态
  item.loading = true
  
  try {
    const response = await downloadSatisfaction({
      templateId: 8,
    })

    const blob = new Blob([response.data], {
      type: response.headers['content-type'],
    })

    // 从 headers 中提取文件名
    let filename = '满意度调查问卷.xlsx'
    const disposition = response.headers['content-disposition']
    if (disposition) {
      const match = disposition.match(/filename="?([^"]+)"?/)
      if (match && match[1]) {
        filename = decodeURIComponent(match[1])
      }
    }

    // 创建下载链接并触发下载
    const url = window.URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = filename
    document.body.appendChild(a)
    a.click()
    a.remove()
    window.URL.revokeObjectURL(url)

    Message.success('下载完成')
  } catch (error) {
    console.error(error)
    Message.error('下载失败，请稍后再试')
  } finally {
    item.loading = false
  }
}

const handleClose = () => {
  emit('close')
}
</script>

<style lang="scss" scoped>
.download-content {
  .download-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15px 0;
    border-bottom: 1px solid #f0f0f0;
    
    &:last-child {
      border-bottom: none;
    }
    
    .item-left {
      .item-name {
        font-size: 14px;
        color: #333;
      }
    }
    
    .item-right {
      .el-button {
        min-width: 80px;
      }
    }
  }
}
</style> 